package com.xunyun.kotlinwc.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.xunyun.kotlinwc.widget.LoadingDialog

/**
 * @author gl
 * @date 2021/9/8
 * @desc
 */
abstract class BaseFragment<T : ViewDataBinding, VM : BaseViewModel> : Fragment() {

    lateinit var mBinding: T
    lateinit var mViewModel: VM
    lateinit var mLoading: LoadingDialog
    lateinit var mContext: Context

    override fun onAttach(context: Context) {
        super.onAttach(context)
        try {
            this.mContext = context;
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = DataBindingUtil.inflate(inflater, getLayoutId(), container, false)
        mViewModel = ViewModelProvider(this, ViewModelProvider.NewInstanceFactory())
            .get(getViewModel()::class.java)
        mBinding.lifecycleOwner = this
        bindViewModel()
        mLoading = LoadingDialog(mContext)
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(view, savedInstanceState)
    }

    abstract fun getLayoutId(): Int
    abstract fun getViewModel(): VM;

    /**
     * 绑定 ViewModel
     */
    abstract fun bindViewModel()
    abstract fun initView(view: View, savedInstanceState: Bundle?)


}